﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OfficeExport;
using XpsConvert;

namespace ConversionApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            UpdateState();
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            // center button
            buttonConvert.Left = (this.ClientSize.Width - buttonConvert.Width) / 2;
        }

        private string SelectFile(bool checkFileExists)
        {
            var dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.CheckFileExists = checkFileExists;
            if (dlg.ShowDialog() == DialogResult.OK) {
                return dlg.FileName;
            }
            return null;
        }

        private void UpdateState()
        {
            this.buttonConvert.Enabled = !string.IsNullOrEmpty(this.textSource.Text) && !string.IsNullOrEmpty(this.textTarget.Text);
        }

        private string DetermineTarget(string source)
        {
            var folder = Path.GetDirectoryName(source);
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(source);
            var extension = Path.GetExtension(source).ToLowerInvariant();
            if (extension == ".xps") {
                var fileName = string.Format("{0}.converted.xps",fileNameWithoutExtension);
                return Path.Combine(folder, fileName);
            }
            else {
                var exporter = ExporterBase.GetExporterForFile(source);
                if (exporter != null) {
                    var fileName = string.Format("{0}{1}", fileNameWithoutExtension, exporter.PreferredFileExtension);
                    return Path.Combine(folder, fileName);
                }
            }

            return null;
        }

        private void SetSource(string source)
        {
            if (source != null) {
                textSource.Text = source;
                textTarget.Text = DetermineTarget(source);

                UpdateState();
            }
        }

        private void buttonSource_Click(object sender, EventArgs e)
        {
            SetSource(SelectFile(true));
        }

        private void buttonTarget_Click(object sender, EventArgs e)
        {
            var target = SelectFile(false);
            if (target != null) {
                textTarget.Text = target;
            }

            UpdateState();
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                e.Effect = DragDropEffects.Copy;
            }
            else {
                e.Effect = DragDropEffects.None;
            }
        }

        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            var data = (string[])e.Data.GetData(DataFormats.FileDrop);
            var fileName = data.First();

            SetSource(fileName);
        }

        private void buttonConvert_Click(object sender, EventArgs e)
        {
            richTextOutput.Clear();

            var source = this.textSource.Text;
            var target = this.textTarget.Text;
            var extension = Path.GetExtension(source).ToLowerInvariant();

            try {
                if (extension == ".xps") {
                    WriteMessage(Color.Black, "Converting images in XPS document...\r\n");
                    var converter = new Converter();
                    var result = converter.Convert(source, target);
                    WriteMessage(Color.Black, "Conversion completed, converted {0} image(s)\r\n", result.ConvertedImageUris.Count());
                    foreach (var uri in result.ConvertedImageUris) {
                        WriteMessage(Color.Black, " {0}\r\n", uri);
                    }
                }
                else {
                    var exporter = ExporterBase.GetExporterForFile(extension);
                    if (exporter != null) {
                        WriteMessage(Color.Black, "Exporting document...\r\n");
                        exporter.Export(source, target);
                        WriteMessage(Color.Black, "Export completed");
                    }
                    else {
                        WriteMessage(Color.Blue, "Cannot convert document '{0}', unknown format.", Path.GetFileName(source));
                    }
                }
            }
            catch (Exception error) {
                WriteMessage(Color.Red, "Conversion failed: {0}\r\n\r\n{1}", error.Message, error);
            }
        }

        private void WriteMessage(Color color, string message, params object[] args)
        {
            var text = string.Format(message, args);

            var start = this.richTextOutput.TextLength;
            this.richTextOutput.AppendText(text);
            var length = this.richTextOutput.TextLength;
            if (start >= 0) {
                this.richTextOutput.SelectionStart = start;
                this.richTextOutput.SelectionLength = length - start;
                this.richTextOutput.SelectionColor = color;
            }
            this.richTextOutput.SelectionStart = length;
            this.richTextOutput.ScrollToCaret();
        }
    }
}
